//
//  PaymentViewController.m
//  Yogofly
//
//  Created by Meracom on 6/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PaymentViewController.h"
#import "UINavigationBar+CustomImage.h"
#import "Utility.h"
#import "AppDelegate.h"

@implementation PaymentViewController

@synthesize btnPayCard;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Step 4";
    
    [[Utility Shared] loadNavigationIOS5];
    
    UIImage *imgHome = [UIImage imageNamed:@"iconRight.png"];
    UIButton *btnHome = [UIButton buttonWithType:UIButtonTypeCustom];
    btnHome.titleLabel.text = @"HOME";

    [btnHome setBackgroundImage:imgHome forState:UIControlStateNormal];
    [btnHome addTarget:self action:@selector(onHome) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btnRight = [[UIBarButtonItem alloc] initWithCustomView:btnHome];
    self.navigationItem.rightBarButtonItem= btnRight;
    btnRight.customView.frame = CGRectMake(0.0f, 0.0f, imgHome.size.width-24, imgHome.size.height-15);

    [btnRight release];
    
    UIImage *imgBack = [UIImage imageNamed:@"iconLeft.png"];
    UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeCustom];
    [btnBack setBackgroundImage:imgBack forState:UIControlStateNormal];
    [btnBack addTarget:self action:@selector(onBack) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btnLeft = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
    self.navigationItem.leftBarButtonItem= btnLeft;
    btnLeft.customView.frame = CGRectMake(0.0f, 0.0f, imgBack.size.width-24, imgBack.size.height-15);
    [btnLeft release];
    // Do any additional setup after loading the view from its nib.
}

- (void)onBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onHome{
    [[AppDelegate navigationControllerInstance] popToRootViewControllerAnimated:YES];
}

- (IBAction)processPurchase:(UIButton *)sender {
    /*
    // This list of items probably comes from elsewhere, but let's hard-code it, by way of example.
    // IMPORTANT: All amounts are in *cents*
    NSArray *itemsToBuy = [NSArray arrayWithObjects:
                           [CardIOChargeRequest itemWithDescription:@"Stuffed puffin" amount:1500],
                           [CardIOChargeRequest itemWithDescription:@"Puffin hat" amount:500],
                           nil];
    
    // Each item must have a description, and the items must total to at least 100 ($1 USD) and at most 100000 ($1000 USD).
    
    // create a CardIOChargeRequest
    CardIOChargeRequest *chargeRequest = [[[CardIOChargeRequest alloc] init] autorelease];
    //chargeRequest.appToken = @"YOUR_APP_TOKEN_HERE"; // get your app token from the card.io website
    chargeRequest.appToken = @"07480d5c816b48c7aa7dbc3a87cd24a4";
    chargeRequest.currency = @"USD"; // must be @"USD"
    chargeRequest.items = itemsToBuy;
    
    //chargeRequest.live = YES; // uncomment for "live" charges (i.e real money will change hands)
    
    // Double-check request validity. If the request is not valid, we'll end up with a nil
    // view controller, which throws an exception if presented.
    NSError *requestError = nil;
    BOOL requestIsValid = [chargeRequest isValid:&requestError];
    if(requestIsValid) {
        CardIOPaymentViewController *charger = [[CardIOPaymentViewController alloc] initWithPaymentDelegate:self
                                                                                              chargeRequest:chargeRequest];
        [self presentModalViewController:charger animated:YES];
        [charger release];
    } else {
        // Oops! An item must be missing a description, or the amounts must not total to an allowable amount.
        // Let the user know here, or log/inspect requestError, or fix the problem...
    }
     */
    CardIOPaymentViewController *scanViewController = [[[CardIOPaymentViewController alloc] initWithPaymentDelegate:self] autorelease];
    scanViewController.appToken = @"07480d5c816b48c7aa7dbc3a87cd24a4"; // get your app token from the card.io website
    [self presentModalViewController:scanViewController animated:YES];
}

#pragma mark - CardIOPaymentViewControllerDelegate model methods
/*
- (void)paymentViewController:(CardIOPaymentViewController *)paymentViewController
       didSucceedWithResponse:(CardIOChargeResponse *)response {
    
    NSLog(@"Charge succeeded with response: %@", response);
    // Do whatever needs to be done to deliver the purchased items.
}

- (void)paymentViewController:(CardIOPaymentViewController *)paymentViewController
             didFailWithError:(NSError *)error {
    
    // Charge failed...don't deliver anything.
    // This should *rarely* happen. Most times, when something goes wrong, card.io
    // will handle the error internally and communicate with the user. This is for
    // exceptional circumstances, such as an invalid or disabled app token.
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Sorry"
                                                    message:@"Unable to complete purchase"
                                                   delegate:nil
                                          cancelButtonTitle:@"Ok"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
    NSLog(@"Error in payment: %@", error);
}

#pragma mark - CardIOPaymentViewControllerDelegate UI methods

- (void)userDidCancelPaymentViewController:(CardIOPaymentViewController *)paymentViewController {
    NSLog(@"User cancelled payment");
    [self dismissModalViewControllerAnimated:YES];
}

- (void)paymentViewControllerDidFinish:(CardIOPaymentViewController *)paymentViewController {
    NSLog(@"Payment view controller finished.");
    [self dismissModalViewControllerAnimated:YES];
}
*/
- (void)userDidCancelPaymentViewController:(CardIOPaymentViewController *)scanViewController {
    NSLog(@"User canceled payment info");
    // Handle user cancellation here...
    [scanViewController dismissModalViewControllerAnimated:YES];
}

- (void)userDidProvideCreditCardInfo:(CardIOCreditCardInfo *)info inPaymentViewController:(CardIOPaymentViewController *)scanViewController {
    // The full card number is available as info.cardNumber, but don't log that!
    NSLog(@"Received card info. Number: %@, expiry: %02i/%i, cvv: %@.", info.redactedCardNumber, info.expiryMonth, info.expiryYear, info.cvv);
    // Use the card info...
    [scanViewController dismissModalViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
